<template>
  <div class="departments-container">
    <div class="app-container">
      <el-card class="department_box box-card">
        <DeptsOptions :row="company" :is-root="true" @addClick="onClickAdd" />
        <!-- 树形结构 -->
        <el-tree :data="depts" :props="defaultProps" :default-expand-all="true">
          <template v-slot="scope">
            <DeptsOptions :row="scope.data" @editClick="onClickEdit" @addClick="onClickAdd" @ondel="loadDepartments" />
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- 弹框 -->
    <AddDept ref="addDept" :row="deptRow" :show-dialog.sync="dialogVisible" @addSuccess="loadDepartments" />
  </div>
</template>

<script>
import { getDepartments } from '@/api/departments'
import { transListToTree } from '@/utils'
import DeptsOptions from './components/DeptsOptions'
import AddDept from './components/AddDept.vue'
export default {
  name: 'Departments',

  components: {
    DeptsOptions,
    AddDept
  },
  data() {
    return {
      defaultProps: {
        label: 'name'
      },
      depts: [],
      company: {}, // 记录公司信息
      dialogVisible: false,
      deptRow: {}
    }
  },

  created() {
    this.loadDepartments()
  },

  methods: {
    async loadDepartments() {
      const res = await getDepartments()
      this.depts = transListToTree('', res.depts)
      this.company = { name: res.companyName, manager: '负责人', children: this.depts }
    },
    // 添加子部门
    onClickAdd(val) {
      this.dialogVisible = true
      this.deptRow = val
    },
    // 查看部门
    onClickEdit(val) {
      this.dialogVisible = true
      this.deptRow = val
      this.$nextTick(() => {
        this.$refs.addDept.serForm()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.department_box {
  .el-tree {
    border-top: 1px solid #ccc;
    margin-top: 10px;
  }
}
</style>
